package org.mnj07.jms.queue;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;

public class Receiver
{
  public static void main(String[] args) {
    try {

        // Gets the JgetTopicName()NDI context
        Context jndiContext = new InitialContext();

        // Looks up the administered objects
        ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee6/ConnectionFactory");
        Queue queue = (Queue) jndiContext.lookup("jms/javaee6/Queue");

        // Creates the needed artifacts to connect to the queue
        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(queue);
        connection.start();

        // Loops to receive the messages
        System.out.println("\nInfinite loop. Waiting for a message...");
        while (true) {
            TextMessage message = (TextMessage) consumer.receive();
            System.out.println("Message received: " + message.getText());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}
